package com.specialtreasure.freightdepot.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.UserUtils;
import com.app.core.view.MarqueeTextView;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.adapter.MyOwnerAdapter;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.BaseZGoodsUserResponse;
import com.specialtreasure.freightdepot.model.ZGoodsUserResponse;
import com.specialtreasure.freightdepot.model.ZGoodsUserResponseData;
import com.specialtreasure.freightdepot.popupwindow.SelectCityPW;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/24 0024.
 * 我的货主
 */

public class MyOwnerActivity extends BaseNewActivity implements View.OnClickListener {

    public static final String TAG = "MyOwnerActivity";
    Integer count = 10;//每页条数
    Integer page = 1;//页数
    Boolean hasMode;
    MyOwnerAdapter myOwnerAdapter;
    List<ZGoodsUserResponse> zGoodsUserResponses = new ArrayList<ZGoodsUserResponse>();
    String belongProvince;//归属地省
    String belongCity;//归属地市
    String belongCounty;//归属地县

    private ImageView iv_back;
    private TextView tv_title;
    private MarqueeTextView tv_navigation;
    private TextView tv_location;
    private RelativeLayout rl_location;
    private ListView lv_moto_cade;
    private PtrClassicFrameLayout ptr_layout;
    private LinearLayout ll_root;
    private TextView tv_sure;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my_owner);
        initView();
        setData();
        getAD();
    }

    private void setData() {
        // 注册对象
        EventBus.getDefault().register(this);

        show(iv_back);
        show(tv_sure);
        tv_title.setText("我的货主");
        tv_sure.setText("添加货主");


        //初始化自动刷新
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);

        //下拉刷新
        ptr_layout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptr_layout.setLoadMoreEnable(true);
                page = 1;
                zGoodsUserResponses.clear();
                getData();

            }
        });

        //自动加载更多
        ptr_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!hasMode) {
                    page++;
                    getData();
                } else {
                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                    ptr_layout.setLoadMoreEnable(false);
                }
            }
        });
    }


    /**
     * 网络请求
     */
    private void getData() {
        String url = Constants.HTTP_URL + HttpApi.MYGOODSUSERS;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("count", count);
        request.add("page", page);
        request.addNull("belongProvince", belongProvince);
        request.addNull("belongCity", belongCity);
        request.addNull("belongCounty", belongCounty);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                ptr_layout.refreshComplete();
                ptr_layout.loadMoreComplete(true);

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseZGoodsUserResponse model = JSON.parseObject(result, BaseZGoodsUserResponse.class);

                if (model != null) {
                    Integer status = model.getStatus();
                    String msg = model.getMsg();
                    //判断状态是
                    if (status != null && status == 0) {
                        ZGoodsUserResponseData data = model.getData();
                        if (data != null) {
                            hasMode = data.getHasMore();
                            //适配数据
                            List<ZGoodsUserResponse> tempList = data.getResultList();
                            if (tempList != null && tempList.size() > 0) {
                                zGoodsUserResponses.addAll(tempList);
                                ptr_layout.setLoadMoreEnable(true);
                            } else {
                                ptr_layout.setLoadMoreEnable(false);
                            }

                            if (myOwnerAdapter == null) {
                                myOwnerAdapter = new MyOwnerAdapter(MyOwnerActivity.this);
                                myOwnerAdapter.setzGoodsUserResponses(zGoodsUserResponses);
                                lv_moto_cade.setAdapter(myOwnerAdapter);
                            } else {
                                myOwnerAdapter.setzGoodsUserResponses(zGoodsUserResponses);
                                myOwnerAdapter.notifyDataSetChanged();
                            }
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });
    }


    /**
     * 获取广告
     */
    private void getAD() {
        String url = Constants.HTTP_URL + HttpApi.ADVERTLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ONE, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);

                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null) {
                    Integer status = jsonObject.getInteger("status");
                    String msg = jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        List<String> data = JSON.parseArray(jsonObject.getJSONArray("data").toString(), String.class);
                        if (data != null && data.size() > 0) {
                            tv_navigation.init(data);
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }

                }

            }


        });
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_navigation = (MarqueeTextView) findViewById(R.id.tv_navigation);
        tv_location = (TextView) findViewById(R.id.tv_location);
        rl_location = (RelativeLayout) findViewById(R.id.rl_location);
        lv_moto_cade = (ListView) findViewById(R.id.lv_moto_cade);
        ptr_layout = (PtrClassicFrameLayout) findViewById(R.id.ptr_layout);
        ll_root = (LinearLayout) findViewById(R.id.ll_root);

        iv_back.setOnClickListener(this);
        rl_location.setOnClickListener(this);
        tv_sure = (TextView) findViewById(R.id.tv_sure);
        tv_sure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_location:
                SelectCityPW pwTo = new SelectCityPW(this);
                pwTo.showAtBottom(ll_root);
                pwTo.setOnResultListener(new SelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            belongProvince = address.province;
                            belongCity = address.city;
                            belongCounty = address.region;
                            tv_location.setText(belongProvince + belongCity + belongCounty);

                            //城市判断
                            if (belongProvince.equals(belongCity)){
                                belongProvince="";
                                tv_location.setText(belongCity+ belongCounty);
                            }

                            if (belongProvince.equals("全国")) {
                                belongProvince = "";
                                tv_location.setText("全国");

                            }

                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);
                        }
                    }

                });
                break;
            case R.id.tv_sure:
                intent.setClass(mContext, AddOwnerActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Subscriber(tag = Constants.UPDATEOWNER)
    private void updateData(BaseModel baseModel) {
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销
        EventBus.getDefault().unregister(this);
    }


    @Override
    public String getActiviyName() {
        return TAG;
    }
}
